﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FsCarInfo.Core.Entity.IRespositories;
using HMIS.FrameWork.Repository.Nhb;
using FsCarInfo.Core.Entity;
using HMIS.FrameWork.DomainBase;
using HMIS.FrameWork.Repository;

namespace FsCarInfo.Core.Entity.IRespositories.Impl
{
	public class BCarRepositoryImpl : RepositoryNhbImpl<BCar>, IBCarRepository
	{
		#region IBCarRepository 成员

		public IList<BCar> GetPlistAll(int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			
			// sort
			string strSort = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;

			// sql条件
			string strSql = @" from BCar as t "
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " where " + strFilter);

			// 查询
			var query = Session.CreateQuery(@"select t " + strSql + strSort);
			if (limit > 0)
				query.SetFirstResult(start).SetMaxResults(limit);

			// 汇总
			total = Session.CreateQuery(@"select count(*) " + strSql)
				.UniqueResult<long>();
			
			return query.List<BCar>();
		}

		public BCar GetById(string id)
		{
			try
			{
				var query = Session.CreateQuery(@"select distinct t from BCar as t
                                                    left join fetch t.AuthorizeUsers
                                                   where t.Id=:Id");
				query.SetString("Id", id);

				IList<BCar> result = query.List<BCar>();

				if (result.Count <= 0)
					throw new RepositoryException("返回实体为空");
				else
					return result[0];
			}
			catch (Exception ex)
			{
				throw new RepositoryException("获取实体失败", ex);
			}
		}

		public bool IsFieldExist(string fieldName, string fieldValue, string id)
		{
			return base.IsFieldExist(fieldName, fieldValue, id, null);
		}

		#endregion
	}
}
